package org.jeecg.common.util;

import cn.hutool.extra.qrcode.QrCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static org.jeecg.modules.vendors.tencent.util.ApplicationYmlUtil.getApplicationYmlConfigByKey;

@Slf4j
public class QrcodeUtil {

    private static final String UPLOAD_FILE_PATH_KEY = "jeecg.path.upload";

    public static String createQrCodeFile(String content, String fileName) {
        try {
            String ctxPath = (String) getApplicationYmlConfigByKey(UPLOAD_FILE_PATH_KEY);;
            log.info("\n\nQrcodeUtil createQrCodeFile cxtPath : {}\n\n", ctxPath );
            String bizPath = "files";
            String nowDay = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(ctxPath + File.separator + bizPath + File.separator + nowDay);
            log.info(file.getPath());
            if (!file.exists()) {
                boolean success = file.mkdirs();// 创建文件根目录
            }

            String savePath = file.getPath() + File.separator + fileName;
            String dbpath = bizPath + File.separator + nowDay + File.separator + fileName;

            byte[] bytes = QrCodeUtil.generatePng(content, 500, 500);
            File saveFile = new File(savePath);
            FileCopyUtils.copy(bytes, saveFile);

            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
